package com.beijiteshop.libcommon.base.activity

import android.os.Bundle
import android.view.Gravity
import android.widget.Toast
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import com.beijiteshop.libcommon.R
import com.beijiteshop.libcommon.ext.databinding.bindView
import com.beijiteshop.libcommon.ext.databinding.viewLifeCycleOwner
import com.beijiteshop.libcommon.login.UserInfoUtil
import com.beijiteshop.libcommon.utils.StatusBarHelper
import com.beijiteshop.libcommon.view.LoadingDialog

/**
 * 基类Activity
 */
abstract class BaseActivity<ActBinding : ViewDataBinding> : AppCompatActivity() {

    protected lateinit var mBinding: ActBinding
    private var mLoadingDialog: LoadingDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarHelper.setStatusBar(this, R.color.colorWhite)
        mBinding = bindView<ActBinding>(getLayoutRes()).also {
            it.lifecycleOwner = viewLifeCycleOwner
        }
        initView(savedInstanceState)
        initData()
        initEvent()
    }

    @LayoutRes
    abstract fun getLayoutRes(): Int

    abstract fun initView(savedInstanceState: Bundle?)

    abstract fun initData()

    abstract fun initEvent()

    override fun onDestroy() {
        super.onDestroy()
        if (this::mBinding.isInitialized) {
            mBinding.unbind()
        }
    }

    /**
     * 扩展用于liveData便捷写法的函数
     * [block]liveData对象，响应change变化的逻辑块
     */
    protected inline fun <T : Any?> LiveData<T>.observeKt(crossinline block: (T?) -> Unit) {
        this.observe(this@BaseActivity, Observer {
            block(it)
        })
    }

    protected fun showToastInCenter(text: String){
        val toast = Toast.makeText(this,text,Toast.LENGTH_SHORT)
        toast.setGravity(Gravity.CENTER,0,0)
        toast.show()
    }

    protected fun showToast(text: String){
        Toast.makeText(this,text,Toast.LENGTH_SHORT).show()
    }
    protected fun showNetErrorToast(text: String? = null){
        Toast.makeText(this,text?:resources.getString(R.string.state_network_error),Toast.LENGTH_SHORT).show()
    }

    protected fun isUserLogin(): Boolean{
        return UserInfoUtil.getInstance().isLogin()
    }

    protected fun showLoading(text: String? = null){
        mLoadingDialog = LoadingDialog.showDialog(supportFragmentManager,text)
    }

    protected fun hideLoading(){
        mLoadingDialog?.dismissDialog()
    }
}